import {Component, OnInit} from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  Validators
} from '@angular/forms';
import {NzMessageService, NzDropdownContextComponent, NzDropdownService, NzMenuItemDirective} from 'ng-zorro-antd';

import {Menu} from './model/menu';

import {I18NService} from '@core/i18n/i18n.service';
import {PopupService} from '@shared/popup/popup.service';
import {MenuService} from './services/menu.service';

import {MenuModifyComponent} from './modify/menu-modify.component';

@Component({
  templateUrl: './menu-list.html'
})
export class MenuListComponent implements OnInit {
  constructor(
    private message: NzMessageService,
    private i18nService: I18NService,
    private menuService: MenuService,
    private fb: FormBuilder,
    private popupService: PopupService
  ) {
    this.validateForm = this.fb.group({
      name: ''
    });
  }

  type = 0;
  data: Menu[] = [];
  page = {
    pageNo: 1,
    pageSize: 20,
    total: 1
  };

  _loading = false;

  expandDataCache = {};

  tempEditObject = {};

  validateForm: FormGroup;

  ngOnInit(): void {
    this.getMenuByPage(true);
  }

  collapse(array, data, $event: boolean): void {
    if ($event === false) {
      if (data.children) {
        data.menuFunctionChilders.forEach(d => {
          const target = array.find(a => a.id === d.id);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [], array = [], hashMap = {};
    stack.push({...root, level: 0, expand: false});
    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.menuFunctionChilders) {
        for (let i = node.menuFunctionChilders.length - 1; i >= 0; i--) {
          stack.push({...node.menuFunctionChilders[i], level: node.level + 1, expand: false, parent: node});
        }
      }
    }
    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.id]) {
      hashMap[node.id] = true;
      array.push(node);
    }
  }

  getMenuByPage(reset = false): void {
    if (reset) {
      this.page.pageNo = 1;
    }
    if (!this._loading) {
      this._loading = true;
      this.menuService.getMenuByPage(this.page.pageNo, this.page.pageSize, this.type, this.validateForm.value.name)
        .subscribe(res => {
          this._loading = false;
          this.data = res.records;
          this.page.total = res.total;
          res.records.forEach(item => {
            this.expandDataCache[item.id] = this.convertTreeToList(item);
            this.tempEditObject[item.id] = {};
          });
        }, err => {
          this._loading = false;
        });
    }
  }


  showModify(item?: any): void {
    let params = {};
    let title = '添加菜单';
    if (item !== undefined) {
      params = {
        id: item.id
      };
      title = item.name + '菜单修改';
    }
    this.popupService.create({
      title: title,
      content: MenuModifyComponent,
      componentParams: params,
      width: 620,
      onSubmit: (res) => {
        this.getMenuByPage(true);
      },
      onCancel: (res) => {
        console.log(res);
      }
    }).afterClose.subscribe(res => {
      console.log(res);
    });
  }

  delete(id: string): void {
    if (!this._loading) {
      this._loading = true;
      this.menuService.deltetMenu(id)
        .subscribe(res => {
          if (res) {
            this.message.success(this.i18nService.translate('modify.return.delete_success'));
            this._loading = false;
            this.getMenuByPage();
          } else {
            this.message.error(this.i18nService.translate('modify.return.delete_error'));
            this._loading = false;
          }
        }, err => {
          this._loading = false;
        });
    }
  }

  search(): void {
    this.getMenuByPage(true);
  }

  refresh(): void {
    this.getMenuByPage(true);
  }

  refreshAuthority(): void {
    this.menuService.refreshAuthority().subscribe();
    this.getMenuByPage(true);
  }
}
